package com.twohand.admin.Service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.twohand.admin.Dto.*;
import com.twohand.admin.Entity.*;
import com.twohand.admin.Mapper.BillMapper;
import com.twohand.admin.Mapper.ShopMapper;
import com.twohand.admin.Service.*;
import com.twohand.admin.Util.JwtUtil;
import com.twohand.admin.Util.PageResponse;
import com.twohand.admin.Vo.*;
import com.twohand.admin.Vo.Order.OrderStatisVo;
import com.twohand.utils.Response.BaseException;
import com.twohand.utils.Response.Response;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class BillServiceImpl implements BillService {
    @Autowired
    BillMapper billMapper;
    @Autowired
    ShopMapper shopMapper;
    @Autowired
    OrderService orderService;
    @Autowired
    SalesmanService salesmanService;
    @Autowired
    ShopService shopService;
    @Autowired
    UserService userService;
    public Logger log = LoggerFactory.getLogger(BillServiceImpl.class);
    @Override
    public List<SelectOptions> getOptions() {
        return billMapper.getOptions();
    }

    @Override
    public PageResponse<Bill> billList(BillListQueryDto billListQueryDto) {
        List<Integer> shopIds = getCurrentUserShopIds();
        PageHelper.startPage(billListQueryDto.getPageNum(),billListQueryDto.getPageSize());
        String billNo = billListQueryDto.getBillNo();
        String status = billListQueryDto.getStatus();
        String activeDate = billListQueryDto.getActiveDate();
        String shopName = billListQueryDto.getShopName();
        String startTime = billListQueryDto.getStartTime();
        String endTime = billListQueryDto.getEndTime();
        Integer platform = billListQueryDto.getPlatform();
        List <Bill> qrcodeList = billMapper.getList(billNo,status,activeDate,shopName,platform,startTime,endTime,shopIds);
        PageInfo<Bill> swipePageInfo = new PageInfo<>(qrcodeList);
        return new PageResponse<Bill>(swipePageInfo,qrcodeList);
    }

    @Override
    public Object addBill(Bill bill) {
        QueryWrapper<Bill> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("bill_no",bill.getBillNo());
        Bill bill1 = billMapper.selectOne(queryWrapper);
        if(bill1 != null){
            throw new BaseException(500,"当前账单编号已存在，不可添加重复账单");
        }
        if(billMapper.insert(bill) > 0){
            updateShopForSid(bill.getShopId());
            return bill;
        }
        return false;
    }

    @Override
    public Boolean changeBill(Bill bill) {
        updateShopForSid(bill.getShopId());
        return billMapper.updateById(bill) > 0;
    }

    @Override
    public Boolean delOBill(Integer id) {
//        //根据id获取BillNo
//        Bill bill = billMapper.selectById(id);
//        //有外键关系
//        List<Order> orderList = orderService.getOrderByBillNo(bill.getBillNo());
//        if(orderList.size()>0){
//            throw  new BaseException(500,"当前账单存在订单，不可删除");
//        }
        Bill bill = billMapper.selectById(id);
        updateShopForSid(bill.getShopId());
        return billMapper.deleteById(id) > 0;
    }

    @Override
    public BillDetailVo getBillDetail(Integer id) {
        if(id == null){
            throw new BaseException(500,"id不能为空!");
        }
        //根据id获取账单
        Bill bill = billMapper.selectById(id);
        BillDetailVo billDetail = new BillDetailVo();
        BeanUtils.copyProperties(bill,billDetail);
        //根据账单Id查询符合要求的订单
        List<Order> orderList = orderService.getOrderByBillNo(billDetail.getBillNo());
        //赋值
        billDetail.setOrderList(orderList);
        return billDetail;
    }

    @Override
    public BillDetailOrderVo getBillDetail(String billNo) {
        //billNo查详情
        if(billNo == null){
            throw new BaseException(500,"参数错误!");
        }
        BillDetailOrderVo billDetail = billMapper.getBillDetailOrder(billNo);
        //根据账单Id查询符合要求的订单
        List<Order> orderList = orderService.getOrderByBillNo(billNo);
        //赋值
        billDetail.setOrderList(orderList);
        return billDetail;
    }

    @Override
    public BillDetailOption getBillOptions() {
        BillDetailOption billDetailOption = new BillDetailOption();
        //销售人员
        List<SelectOptions> salesOptions = salesmanService.getSalesOptions();
        billDetailOption.setSalesOption(salesOptions);
        return billDetailOption;
    }

    @Override
    public PageResponse<BillSearchResult> getBillDetailList(BillDetailListDto billDetailListDto) throws ParseException {
        PageHelper.startPage(billDetailListDto.getPageNum(),billDetailListDto.getPageSize());
        QueryWrapper<BillSearchResult> queryWrapper = new QueryWrapper<>();

        // 判断是否有设置关联
        Shop shop = shopService.selectShopById( billDetailListDto.getId());
        List <BillSearchResult> billDetailList = new ArrayList<>();
        if(StringUtils.isNoneEmpty(shop.getRelevancy())){
            billDetailList  = billMapper.getBillDetailListByRelevancy(shop.getRelevancy(),billDetailListDto.getActiveDate(),billDetailListDto.getStatus(),null);
        }else{
            billDetailList = billMapper.getBillDetailListById(billDetailListDto.getId(),billDetailListDto.getActiveDate(),billDetailListDto.getStatus(),null);
        }


//        Map<String,List<BillSearchResult>> map = new HashMap<>();
//        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-mm-dd");
//        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年mm月");
//        for (BillSearchResult b: billDetailList) {
//            String activeDate = b.getActiveDate();
//            String text = sdf2.format(sdf1.parse(activeDate));
//            if(map.get(text) == null){
////                List<BillSearchResult> bs = new
//                map.put(text,new ArrayList<BillSearchResult>());
//            }
//            map.get(text).add(b);
//        }
        PageInfo<BillSearchResult> swipePageInfo = new PageInfo<>(billDetailList);
        return new PageResponse<BillSearchResult>(swipePageInfo,billDetailList);
    }

    @Override
    public Object checkAndAddBill(List<BillInfoDto> billInfos) {
//        Salesman salesman = salesmanService.getDefaultSales();
        Integer success = 0;
        for (BillInfoDto billInfo:billInfos) {
            String billNo = billInfo.getBillNo();
            QueryWrapper<Bill> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("bill_no",billNo);
            Bill bill = billMapper.selectOne(queryWrapper);
            if(bill==null){
                bill = new Bill();
                String activeDate = billInfo.getActiveDate();
                //根据shopName 获取sid
                String shopName = billInfo.getShopName();
                Shop shop = shopService.selectShopByNameAndPlatform(shopName,billInfo.getPlatform());
                if(shop == null){
                    log.info("创建单据中:————店铺:"+shopName+"为创建创建失败");
                    throw new BaseException(500,"店铺:"+shopName+"添加失败，请重试或手动添加");
                }
                //店铺更新了

                bill.setBillNo(billNo);
                bill.setActiveDate(activeDate);
                bill.setShopId(shop.getId());
                Integer res = billMapper.insert(bill);
                success+=1;
                log.info("账单:"+billNo+"不存在，创建结果:"+res);
            }
            updateShopForSid(bill.getShopId());

        }
        return new Response(203,"成功添加账单"+success+"个",null);
    }

    @Async
    @Override
    public void updateShopForSid(Integer shopId) {
        LambdaQueryWrapper<Shop> shopLambdaQueryWrapper = new LambdaQueryWrapper<>();
        shopLambdaQueryWrapper.eq(Shop::getId,shopId);
        Shop shop = shopMapper.selectOne(shopLambdaQueryWrapper);
        if(shop!=null){
            shopService.updateUrlIsNotGen(shop.getShopName(),shop.getId());
        }
    }

    @Override
    public OrderStatisVo getOrderTotal(BillListQueryDto billListQueryDto) {
        String billNo = billListQueryDto.getBillNo();
        String status = billListQueryDto.getStatus();
        String activeDate = billListQueryDto.getActiveDate();
        String shopName = billListQueryDto.getShopName();
        Integer plathform = billListQueryDto.getPlatform();
        String startTime = billListQueryDto.getStartTime();
        String endTime = billListQueryDto.getEndTime();
        List<Integer> shopIds = getCurrentUserShopIds();
        OrderStatisVo orderStatisVo =  billMapper.orderMoneyTotal(billNo,status,activeDate,shopName,plathform,startTime,endTime,shopIds);
        if(orderStatisVo==null)orderStatisVo = new OrderStatisVo();
        return orderStatisVo;
    }

    @Override
    public Boolean batchChangeStatus(BatchChangeStatusDto batchChangeStatusDto) {
        List<String> ids = batchChangeStatusDto.getIds();
        if(ids.size()==0){
            throw new BaseException(500,"未勾选账单！");
        }
        return billMapper.batchChangeStatus(ids,batchChangeStatusDto.getStatus()) > 0;
    }

    @Override
    public List<Integer> getCurrentUserShopIds() {
        User user = JwtUtil.getCurrentUser();
        User user1 = userService.getUserById(user.getId());
        if(user1.getSid()!=0){
           List<Integer> list =  shopService.getSalesShop(user1.getSid(),null,null).stream().map(Shop::getId).collect(Collectors.toList());
           return list;
        }
        return null;
    }

    @Override
    public Map batchChangeShop(BatchChangeShopDto batchChangeShopDto) {
        List<String> ids = batchChangeShopDto.getIds();
        Integer shopId = batchChangeShopDto.getShopId();
        //判断是否勾选了账单
        if(ids.size()==0){
            throw new BaseException(500,"未勾选账单！");
        }
        //判断店铺是否存在
        Shop shop = shopService.getShopById(shopId);
        if(shop == null){
            throw new BaseException(500,"无效的店铺！");
        }
        Boolean status = billMapper.batchChangeShop(ids,shop.getId()) > 0;
        Map map = new HashMap();
        map.put("status",status);
        map.put("shopName",shop.getShopName());
        return map;
    }


}
